//
//  NSDictionary+Hook.m
//  InduceTool
//
//  Created by 魏延龙 on 2020/9/18.
//  Copyright © 2020 魏延龙. All rights reserved.
//

#import "NSDictionary+Hook.h"
#import <objc/runtime.h>

@implementation NSDictionary (Hook)

+(void)load {
    Method oriInit = class_getClassMethod(self, @selector(dictionaryWithObject:forKey:));
    Method extInit = class_getClassMethod(self, @selector(hookDictionaryWithObject:forKey:));
    method_exchangeImplementations(oriInit, extInit);
    
    
    // @{@"":@""} 这种初始化方式 等价于 dictionaryWithObjects:forKeys:count:
    Method oriInitWithCount = class_getClassMethod(self, @selector(dictionaryWithObjects:forKeys:count:));
    Method extInitWithCount = class_getClassMethod(self, @selector(hookDictionaryWithObjects:forKeys:count:));
    method_exchangeImplementations(oriInitWithCount, extInitWithCount);
}

+ (instancetype) hookDictionaryWithObject:(id)object forKey:(id)key
{
    if (object && key) {
        return [self hookDictionaryWithObject:object forKey:key];
    }
    return nil;
}
+ (instancetype) hookDictionaryWithObjects:(const id [])objects forKeys:(const id [])keys count:(NSUInteger)cnt
{
    NSInteger index = 0;
    id ks[cnt];
    id objs[cnt];
    for (NSInteger i = 0; i < cnt ; ++i) {
        if (keys[i] && objects[i]) {
            ks[index] = keys[i];
            objs[index] = objects[i];
            ++index;
        }
    }
    return [self hookDictionaryWithObjects:objs forKeys:ks count:index];
}

@end
